﻿using MongoDB.Driver;
using Sustainalytics.Entities;
using Sustainalytics.Entities.RiskRatings;
using Sustainalytics.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.RiskRatings.Service.Controllers.Company
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/company/{companyId}")]
    public class IndicatorController : ApiController
    {
        private static readonly IndicatorCodeComparer indicatorComparer = new IndicatorCodeComparer();
        private readonly IMongoCollection<ComprehensiveRiskRatingIndicator> _indicatorCollection;
        private readonly IMongoCollection<CoreRiskRatingIndicator> _coreIndicatorCollection;
        private readonly IMongoCollection<GovernancePillars> _pillarsCollection;

        public IndicatorController(
            IMongoCollection<ComprehensiveRiskRatingIndicator> indicatorCollection,
            IMongoCollection<CoreRiskRatingIndicator> coreIndicatorCollection,
            IMongoCollection<GovernancePillars> pillarsCollection)
        {
            _indicatorCollection = indicatorCollection;
            _coreIndicatorCollection = coreIndicatorCollection;
            _pillarsCollection = pillarsCollection;
        }

        [Route("mei/{externalId}/indicator/{code}")]
        public async Task<HttpResponseMessage> Get(Guid companyId, int externalId, string code)
        {
            code = code.Replace("_", ".");
            var @indicator = await _indicatorCollection.Find(e => e.CompanyId == companyId && e.MeiExternalId == externalId && e.Code == code).FirstOrDefaultAsync().ConfigureAwait(false);

            if (@indicator == null)
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);

            return Request.CreateResponse(System.Net.HttpStatusCode.OK, new
            {
                AnswerCategoryText = @indicator.AnswerCategoryText.Value,
                Comment = @indicator.Comment.Value,
                CheckBoxes = @indicator.CheckBoxes.Select(x => new
                {
                    x.Text,
                    IsChecked = x.IsChecked.Value
                }),
                Sources = indicator.Sources?.OrderBy(x => x)
            });
        }

        [Route("indicator/{code}")]
        public async Task<HttpResponseMessage> Get(Guid companyId, string code)
        {
            code = code.Replace("_", ".");
            var @indicator = await _coreIndicatorCollection.Find(e => e.CompanyId == companyId && e.Code == code).FirstOrDefaultAsync().ConfigureAwait(false);

            if (@indicator == null)
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);

            return Request.CreateResponse(System.Net.HttpStatusCode.OK, new
            {
                @indicator.Code,
                @indicator.Name,
                RawScore = @indicator.RawScore.Value,
                FinalWeight = @indicator.FinalWeight.Value,
                WeightedScore = @indicator.WeightedScore.Value,
                Category = @indicator.AnswerCategory.Value,
                AnswerCategoryText = @indicator.AnswerCategoryText.Value,
                CheckBoxes = @indicator.CheckBoxes?.Select(x => new
                {
                    x.Text,
                    IsChecked = x.IsChecked.Value
                }),
                Comment = @indicator.Comment.Value,
                Sources = @indicator.Sources?.OrderBy(x => x),
                @indicator.IndicatorType,
                IsIdiosyncratic = @indicator.IsIdiosyncratic.Value
            });
        }

        [Route("pillar/{number}")]
        public async Task<HttpResponseMessage> GetPillar(Guid companyId, string number)
        {
            number = number.Replace("_", ".");
            var pillar = await _pillarsCollection.Find(x=>x.CompanyId == companyId && x.Number == number).FirstOrDefaultAsync().ConfigureAwait(false);

            if (pillar == null)
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);

            return Request.CreateResponse(System.Net.HttpStatusCode.OK, new
            {
               Indicators = pillar.Indicators.OrderBy(x=> x.Number, indicatorComparer),
               pillar.Comment             
            });
        }
    }
}
